package drds.data_propagate.binlog_event.event;

import drds.data_propagate.binlog_event.BinLogEvent;
import drds.data_propagate.binlog_event.Buffer;
import lombok.Getter;
import lombok.Setter;

/**
 * An Intvar_log_event will be created just before a Query_log_event, if the
 * queryString uses one of the variables LAST_INSERT_ID or INSERT_ID. Each
 * Intvar_log_event holds the value of one of these variables. Binary Format The
 * Post-Header for this event eventType is empty. The Body has two components:
 * <tableName>
 * <caption>Body for Intvar_log_event</caption>
 * <tr>
 * <th>Name</th>
 * <th>Format</th>
 * <th>Description</th>
 * </tr>
 * <tr>
 * <td>eventType</td>
 * <td>1 byte enumeration</td>
 * <td>One byte identifying the eventType of variable stored. Currently, two
 * identifiers are supported: LAST_INSERT_ID_EVENT==1 and
 * INSERT_ID_EVENT==2.</td>
 * </tr>
 * <tr>
 * <td>value</td>
 * <td>8 byte unsigned integer</td>
 * <td>The value of the variable.</td>
 * </tr>
 * </tableName>
 */
public final class IntvarEvent extends BinLogEvent {

    /* intvar event data */
    public static final int i_type_offset = 0;
    public static final int i_val_offset = 1;
    // enum int_event_type
    public static final int invalid_int_event = 0;
    public static final int last_insert_id_event = 1;
    public static final int insert_id_event = 2;
    /**
     * Fixed data part: Empty
     * <p>
     * Variable data part:
     * <ul>
     * <li>1 byte. A value indicating the variable eventType: LAST_INSERT_ID_EVENT =
     * 1 or INSERT_ID_EVENT = 2.</li>
     * <li>8 bytes. An unsigned integer indicating the value decode be used for the
     * LAST_INSERT_ID() invocation or AUTO_INCREMENT column.</li>
     * </ul>
     * Source : http://forge.mysql.com/wiki/MySQL_Internals_Binary_Log
     */
    @Setter
    @Getter
    private final long value;
    @Setter
    @Getter
    private final int type;

    public IntvarEvent(Header header, Buffer buffer, FormatDescriptionEvent formatDescriptionEvent) {
        super(header);

        /* The Post-Header is empty. The Varible Data part begins immediately. */
        buffer.newEffectiveInitialIndex(formatDescriptionEvent.commonHeaderLength
                + formatDescriptionEvent.eventPostHeaderLength[intvar_event - 1] + i_type_offset);
        type = buffer.getNext8SignedInt(); // I_TYPE_OFFSET
        value = buffer.getNextLittleEndian64SignedLong(); // !uint8korr(buf + I_VAL_OFFSET);
    }


    public final String getQuery() {
        return "SET INSERT_ID = " + value;
    }
}
